import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo,
} from "@/utils/auth";
import { resetRouter, allRouters } from "@/router";
const { asyRoutes, constantRoutes } = allRouters;
const { asyncRoutes } = allRouters;
import router from "@/router";
import { isBoolean } from "lodash";
// 定义一个函数：两个数组进行对比，对比出当前用户到底需要显示哪些异步路由信息
const getAsyncRouters = (routers, asyncRoutes1) => {
  // 根据接口返回来的数据进行一下排序展示问题
  function sortArr(jkarr, bdarr) {
    const arr = [];
    for (const i in jkarr) {
      const oldlist = jkarr[i];
      const newlist = bdarr.filter((t) => t.name === oldlist.name);
      if (newlist.length > 0) {
        // 防止修改源路由文件
        const list01 = { ...newlist[0] }
        isBoolean(oldlist.title ? (list01.meta.title = oldlist.title) : list01.title = newlist[0].title);
        isBoolean(oldlist.path ? (list01.path = oldlist.path) : list01.path = newlist[0].path);
        if (oldlist.children && oldlist.children.length) {
          if (list01.children && list01.children.length) {
            list01.children = sortArr(oldlist.children, list01.children);
          } else {
            list01.children = [];
          }
        } else {
          list01.children = [];
        }
        arr.push(list01);
      }
    }
    return arr;
  }
  // 获取到全部路由
  // const allrou = getAsyncRoutersF(routers, asyncRoutes);
  // 获取到全部路由 并排序
  const arr = sortArr(routers, asyncRoutes1);
  return arr;
};

const getDefaultState = () => {
  return {
    token: getToken(), // token存入
    username: getUserInfo().username, // 账号
    name: "", // 用户姓名
    avatar: "", // 用户头像
    address: "",
    btnrouters: [],
    routers: [
      {
        name: "Home",
        title: "首页",
        path: "/",
        children: [{ name: "ShipAgencyHome" },{ name: 'CoalHome',title: "货主首页" }],
      },
      {
        name: "Customer",
        title: "业务中心",
        children: [
          { name: "Carsgjh" },
          { name: "Carjgjh" },
          { name: "ShipJwl" },
          { name: "ShipCy" },
          { name: "CustomerContract" },
          { name: "EntrustXship" },
          { name: "EntrustZship" },
          { name: "ProceduresCar" },
          { name: "ProcedurestTh" },
          { name: "ChangeHq" },
          { name: "EntrustCzy" },
          { name: "ShipBg" },
          { name: "ShipLb" },
          { name: "ShipFile" },
          { name: "BillingQuery" },
          { name: "CdgdApply" },
        ],
      },
      {
        name: "DataCenter",
        title: "数据中心",
        children: [
          { name: "ShipDynamic" },
          { name: "Iframe" },
          { name: "ShipDynamicBB" },
          { name: "ProductionPerformance" },
          { name: "FeeRecord" },
          { name: "GcAccount" },
          { name: "ClearharbourCar" },
          { name: "HailingCar" },
          { name: "WeighingRecord" },
          { name: "CarTj" },
          { name: "PileIn" },
          { name: "PileOut" },
          { name: "PileStock" },
          { name: "CagroTz" },
          { name: "Ywccartj" },

        ],
      },
      {
        name: "VideoCenter",
        title: "视频中心",
        children: [{ name: "VideoPile" }, { name: "VideoShipDynamic" }],
      },
      {
        name: "ConsultingCenter",
        title: "咨询中心",
        children: [{ name: "CooperationOpportunities" }, { name: "MyPost" }],
      },
      {
        name: "CustomerService",
        children: [
          { name: "OperationFlow" },
          { name: "ContactUs" },
          { name: "NameChange" },
          { name: "RefundApply" },
          { name: "KhNameChange" },
          { name: "MatterFiles" }
        ],
      },
      {
        name: "Enterprise",
        children: [
          { name: "Enterprise" },
          { name: "CustomerProfile" },
          { name: "Jbr" },
        ],
      },
    ],
    roles: getUserInfo().roles, // 所有角色信息
    rolescode: getUserInfo().rolescode, // 当前角色
    rolesname: getUserInfo().rolesname, // 当前角色
    invaliddate: getUserInfo().rolesname, // 失效日期
    asyncRoles: [], // 用户当前的橘色
    asyncRouters: [], // 接口中的路由信息
    asyAllRouters: [], // 页面所有的路由信息
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERNAME: (state, username) => {
    state.username = username;
  },
  SET_ADDRESS: (state, address) => {
    state.address = address;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_ROLESCODE: (state, code) => {
    state.rolescode = code;
  },
  SET_ROLESNAME: (state, name) => {
    state.rolesname = name;
  },
  SET_INVALIDDATE: (state, name) => {
    state.invaliddate = name;
  },
  SET_DEFAULTSTATE: (state, userinfo) => {
    // Object.assign(state, userinfo);
    state.name = userinfo.name || "未命名";
    state.asyncRouters = userinfo.roles;
    const url = `${process.env.VUE_APP_API1}/attach/upload/touxiang.jpg`;
    // state.avatar = userinfo.avatar;
    state.avatar = url;
    state.btnrouters = userinfo.btnrouters;
  },
  SET_ASYALLROUTERS: async(state, routers) => {
    resetRouter();
    if (process.env.NODE_ENV === "production") {
      state.routers = routers;
    }
    //  vuex报错当前用户的异步路由，注意，一个用户需要展示完成路由：常量，异步，任意路由
    // state.asyncRouters = getAsyncRouters(routers, asyncRoutes);
    // 备份一下异步路由
    // const asyncAll = JSON.parse(JSON.stringify(asyncRoutes));
    state.asyncRouters = getAsyncRouters(state.routers, asyncRoutes);
    // 还原备份  也是停离谱的，深拷贝的话报错
    // asyncRoutes = asyncAll;
    // 计算出当前用户需要展示的路由信息
    state.asyAllRouters = constantRoutes.concat(state.asyncRouters);
    state.asyAllRouters.push(asyRoutes);
    // 给路由器添加新的路由
    router.addRoutes(state.asyAllRouters);
  },
};
const actions = {
  // 用户登录
  async login({ commit }, userInfo) {
    const { username, password,yzm } = userInfo;
    const result = await this._vm.$api.user.login({
      username: username.trim(),
      yzm: yzm.trim(),
      password: this._vm.md5(password),
    });
    const { token, shipperlist } = result;
    commit("SET_TOKEN", token);
    commit("SET_ROLES", shipperlist);
    commit("SET_USERNAME", username);
    // 本地化存储用户信息
    setUserInfo({ username, roles: shipperlist });
    // token存储
    // setToken(token);
  },
  // 用户切换角色
  async tabRoles({ commit, state }, roles) {
    const { rolescode } = roles;
    const result = await this._vm.$api.user.tabRoles({
      shippercode: rolescode,
      token: state.token,
    });
    const { token } = result;
    commit("SET_TOKEN", token);
    // 本地化存储用户信息
    setToken(token);
  },
  // get user info
  async getInfo({ commit, state }) {
    const result = await this._vm.$api.user.getUserInfo();
    if (!result) {
      return Promise.reject("Verification failed, please Login again.");
    }
    if (!result.name) {
      result.name = "未命名"
    }
    const userInfo = getUserInfo();
    const rolescode = result.shippercode
    const rolesname = result.shippername
    const address = result.address
    const invaliddate = result.invaliddate
    setUserInfo({ ...userInfo, rolescode, rolesname,invaliddate });
    commit("SET_ROLESCODE", rolescode);
    commit("SET_ROLESNAME", rolesname);
    commit("SET_INVALIDDATE", invaliddate);
    commit("SET_ADDRESS", address);
    commit("SET_DEFAULTSTATE", result);
    commit("SET_ASYALLROUTERS", result.routers);
    Promise.resolve(result);
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken(); // must remove  token  first
      resetRouter();
      commit("RESET_STATE");
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      removeUserInfo();
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
